package org.feifei.basic.interceptor;

import org.feifei.basic.constant.LoginConstant;
import org.feifei.user.domain.LoginInfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author forever
 * @Description: 自定义登录拦截器
 * @date 2021/12/09 18:30
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断该次请求是否携带token
        String token = request.getHeader(LoginConstant.LOGIN_TOKEN_KEY);
        if (token != null) {
            // 从redis从判断此时登录是否失效
            LoginInfo loginInfo = (LoginInfo) redisTemplate.opsForValue().get(token);
            if (loginInfo != null) {
                // 重置时间并且放行
                redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);
                System.out.println("执行一次");
                return true;
            }
        }
        // 设置响应头
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        // 响应体
        response.getWriter().write("{\"success\" : false, \"msg\" : \"noLogin\", \"data\" : null}");
        System.out.println("false执行");
        return false;
    }
}